#include "MainWindow.h"
#include "Model.h"

#include <QMenuBar>
#include <QVBoxLayout>
#include <QToolBar>
#include <QLabel>
#include <QTreeView>
#include <QDebug>
#include <QListView>
#include <QSlider>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , m_model(nullptr)
    , m_selectedAlbumIndex(-1)
    , m_spriteSizeScale(1.0)
{
    // pre data init
    m_model = new Model();

    // ui init
    QMenuBar *menuBar = this->menuBar();

    QMenu *fileMenu = new QMenu(this);
    fileMenu->setTitle("文件");
    QAction *openSffFileAction = new QAction("打开Sff文件", this);
    fileMenu->addAction(openSffFileAction);
    QAction *openAirFileAction = new QAction("打开Air文件", this);
    fileMenu->addAction(openAirFileAction);
    QAction *exportAction = new QAction("导出图片、精灵信息和动画信息", this);
    fileMenu->addAction(exportAction);
    menuBar->addMenu(fileMenu);

    QMenu *helpMenu = new QMenu(this);
    helpMenu->setTitle("帮助");
    QAction *aboutAction = new QAction("关于", this);
    helpMenu->addAction(aboutAction);
    menuBar->addMenu(helpMenu);

    // main layout
    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->setContentsMargins(0, 0, 0, 0);

    QWidget *mainWidget = new QWidget(this);
    mainWidget->setLayout(mainLayout);

    setCentralWidget(mainWidget);

    QHBoxLayout *contentLayout = new QHBoxLayout;
    contentLayout->setContentsMargins(0, 0, 0, 0);
    contentLayout->setSpacing(0);
    mainLayout->addLayout(contentLayout);

    // left content
//    contentLayout->addSpacing(3);
    QVBoxLayout *leftContentLayout = new QVBoxLayout;
    leftContentLayout->setContentsMargins(0, 0, 0, 0);
    contentLayout->addLayout(leftContentLayout);

    leftContentLayout->addSpacing(5);
    QLabel *leftContentTitleLabel = new QLabel(this);
    leftContentTitleLabel->setText(" 动画");
    leftContentLayout->addWidget(leftContentTitleLabel, 0, Qt::AlignLeft | Qt::AlignTop);

    leftContentLayout->addSpacing(5);
    QListView *itemListView = new QListView(this);
    itemListView->setIconSize(QSize(30, 30));
    // itemListView->setWordWrap(true);
    itemListView->setEditTriggers(QTreeView::EditTrigger::NoEditTriggers);
//    itemTreeView->setStyleSheet("background-color:yellow");
    leftContentLayout->addWidget(itemListView, 0, Qt::AlignLeft);

    QStandardItemModel *itemListViewModel = new QStandardItemModel(this);
    itemListView->setModel(itemListViewModel);

    // right content
    contentLayout->addSpacing(3);
    QVBoxLayout *rightContentLayout = new QVBoxLayout;
    rightContentLayout->setContentsMargins(0, 0, 0, 0);
    contentLayout->addLayout(rightContentLayout, 1);

    // map title layout
    rightContentLayout->addSpacing(5);
    QLabel *rightContentTitleLabel = new QLabel(this);
//    rightContentTitleLabel->setStyleSheet("background-color:red");
    rightContentTitleLabel->setText("精灵列表");
    rightContentLayout->addWidget(rightContentTitleLabel, 0, Qt::AlignLeft | Qt::AlignVCenter);

    QListView *spriteListView = new QListView(this);
    spriteListView->setIconSize(QSize(30, 30));
    spriteListView->setMaximumHeight(this->height() / 2);
    spriteListView->setWordWrap(true);
    spriteListView->setEditTriggers(QTreeView::EditTrigger::NoEditTriggers);
//    itemTreeView->setStyleSheet("background-color:yellow");
    rightContentLayout->addWidget(spriteListView);

    QStandardItemModel *spriteListViewModel = new QStandardItemModel(this);
    spriteListView->setModel(spriteListViewModel);

    QHBoxLayout *spriteViewTitleLayout = new QHBoxLayout;
    spriteViewTitleLayout->setContentsMargins(0, 0, 0, 0);
    spriteViewTitleLayout->setSpacing(0);
    rightContentLayout->addLayout(spriteViewTitleLayout);

    QLabel *spriteViewTitleLabel = new QLabel(this);
    spriteViewTitleLabel->setText("精灵视图");
    spriteViewTitleLayout->addWidget(spriteViewTitleLabel, 0, Qt::AlignLeft);

    spriteViewTitleLayout->addSpacing(40);
    QLabel *spriteSizeScaleLabel = new QLabel(this);
    spriteSizeScaleLabel->setText("放大率：");
    spriteViewTitleLayout->addWidget(spriteSizeScaleLabel, 0, Qt::AlignLeft);

    QSlider *spriteSizeScaleSlider = new QSlider(this);
    spriteSizeScaleSlider->setFixedWidth(200);
    spriteSizeScaleSlider->setRange(10, 100);
    spriteSizeScaleSlider->setOrientation(Qt::Orientation::Horizontal);
    spriteViewTitleLayout->addWidget(spriteSizeScaleSlider, 0, Qt::AlignLeft);

    spriteViewTitleLayout->addSpacing(5);
    QLabel *spriteSizeScaleValueLabel = new QLabel(this);
    spriteSizeScaleValueLabel->setText("1.0");
    spriteViewTitleLayout->addWidget(spriteSizeScaleValueLabel, 0, Qt::AlignLeft);
    spriteViewTitleLayout->addStretch(1);

    QFrame *spriteView = new QFrame(this);
    spriteView->setFrameShape(QFrame::Shape::Box);
    QVBoxLayout *spriteViewLayout = new QVBoxLayout;
    spriteViewLayout->setContentsMargins(0, 0, 0, 0);
    spriteView->setLayout(spriteViewLayout);
    rightContentLayout->addWidget(spriteView, 1);

    QLabel *spriteViewLabel = new QLabel(spriteView);;
    spriteViewLabel->setScaledContents(true);
    spriteViewLayout->addWidget(spriteViewLabel, 0, Qt::AlignCenter);

    // connect
    connect(fileMenu, &QMenu::triggered, this, [ = ](QAction * action) {
        if (action == openSffFileAction) {
            this->setWindowTitle("MugenResEditor（加载中...）");
            m_sffFilePath = m_model->OpenLoadSffFileDlg();
            QFileInfo sffFileInfo(m_sffFilePath);
            QFileInfo airFileInfo(m_airFilePath);
            this->setWindowTitle("MugenResEditor [" +
                                 sffFileInfo.fileName() + "、" +
                                 airFileInfo.fileName()
                                 + "]");
        }
        if (action == openAirFileAction) {
            this->setWindowTitle("MugenResEditor（加载中...）");
            m_airFilePath = m_model->OpenLoadAirFileDlg();
            QFileInfo sffFileInfo(m_sffFilePath);
            QFileInfo airFileInfo(m_airFilePath);
            this->setWindowTitle("MugenResEditor [" +
                                 sffFileInfo.fileName() + "、" +
                                 airFileInfo.fileName()
                                 + "]");
        }
        if (action == exportAction) {
            const QString &windowTitleStr = windowTitle();
            this->setWindowTitle("MugenResEditor（导出中...）");
            m_model->OpenExportFileDlg();
            this->setWindowTitle(windowTitleStr);
        }
    });

    connect(m_model, &Model::LoadAirFinished, this, [ = ] {
        itemListViewModel->clear();
        const QList<Action> &list = m_model->GetActionList();
        for (const Action &a : list) {
            QString name = QString("（%1）%2").arg(a.Id).arg(QString::fromStdString(a.Name));
           QStandardItem *item = new QStandardItem(name);
           itemListViewModel->appendRow(item);
        }

        if (list.size()) {
           const QModelIndex &currentIndex = itemListViewModel->index(0, 0);
           itemListView->setCurrentIndex(currentIndex);
           Q_EMIT itemListView->clicked(currentIndex);
        }
    });

    connect(itemListView, &QListView::clicked, this, [ = ](const QModelIndex & modelIndex) {
        m_selectedAlbumIndex = modelIndex.row();
        const QModelIndex lastSelectedSpriteListViewIndex = spriteListView->currentIndex();
        const QList<Action> &actionList = m_model->GetActionList();
        const Action &a = actionList.at(m_selectedAlbumIndex);
        const QList<Sprite> &spriteList = m_model->GetSpriteListByAction(a);
        spriteListViewModel->clear();
        for (const Sprite &sprite : spriteList) {
            const QString itemTitle = QString("%1, w: %2, h: %3, ox: %4, oy: %5")
                                          .arg(sprite.Number).arg(sprite.W).arg(sprite.H)
                                          .arg(sprite.OX).arg(sprite.OY);
            QStandardItem *item = new QStandardItem(itemTitle);
            spriteListViewModel->appendRow(item);
        }

        if (spriteList.size()) {
            QModelIndex currentIndex = spriteListViewModel->index(0, 0);
            if (lastSelectedSpriteListViewIndex.row() >= 0 &&
                lastSelectedSpriteListViewIndex.row() < spriteListViewModel->rowCount())
            {
                currentIndex = spriteListViewModel->index(lastSelectedSpriteListViewIndex.row(), 0);
            }
           spriteListView->setCurrentIndex(currentIndex);
           Q_EMIT spriteListView->clicked(currentIndex);
        }
    });

    connect(spriteListView, &QListView::clicked, this, [ = ](const QModelIndex & modelIndex) {
        int selectedSpriteIndex = modelIndex.row();
        const QList<Action> &actionList = m_model->GetActionList();
        const Action &a = actionList.at(m_selectedAlbumIndex);
        const QList<Sprite> &spriteList = m_model->GetSpriteListByAction(a);
        const Sprite &sprite = spriteList.at(selectedSpriteIndex);

        m_currentSprite = sprite;
        spriteViewLabel->setFixedSize(m_currentSprite.W * m_spriteSizeScale,
                                      m_currentSprite.H * m_spriteSizeScale);
       const QImage &img = m_model->GetSpriteImg(sprite);
       spriteViewLabel->setPixmap(QPixmap::fromImage(img));
    });

    connect(spriteSizeScaleSlider, &QSlider::valueChanged, this, [=](int value) {
        // qDebug() << value;
        // float lastSpriteSizeScale = m_spriteSizeScale;
        m_spriteSizeScale = 10 * (value / 100.0);
        spriteSizeScaleValueLabel->setText(QString::number(m_spriteSizeScale, 'g', 2));

        spriteViewLabel->setFixedSize(m_currentSprite.W * m_spriteSizeScale,
                                      m_currentSprite.H * m_spriteSizeScale);
    });

    // post init
}

MainWindow::~MainWindow()
{
}
